/**
 * Created by mikezhangding on 20/2/2017.
 */
'use strict';

app.config(function ($httpProvider) {
  $httpProvider.interceptors.push('AuthInterceptor');
});
app.factory('AuthInterceptor', function ($rootScope, $q, $localStorage, $location) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      if ($localStorage.nonce && $localStorage.loginName && $localStorage.token) {
        config.headers['loginName'] = $localStorage.loginName;
        config.headers['nonce'] = $localStorage.nonce;
        config.headers['token'] = $localStorage.token;
      }
      return config;
    },
    response: function (response) {
      if (response.data.code == '00000004') {
        $location.url('/login');
        return $q.reject(response);
      }
      return response;
    },
    responseError: function (response) {
      if (response.status == 401) {
        if ($location.$$path != "/app/homepage") {
          $location.url('/login');
        }
      }
      return $q.reject(response);
    }
  };
});

app.controller('adminLoginCtrl', function ($rootScope, $state, $scope, $http, $localStorage, $ionicHistory,storageService) {
  $scope.rememberMe = true;
  $scope.account = {
      loginName : storageService.get('loginName'),
      password : storageService.get('password'),
  };

  $scope.isPassword = false;
  $scope.isSelected =function () {
      $scope.isPassword = true;
  }
  $scope.login = function () {
    if($scope.isPassword){
        storageService.set('loginName',$scope.account.loginName);
        storageService.set('password',$scope.account.password);
    }
    $scope.authError = false;
    $http.get(API('huanbi/security/singIn?account='+$scope.account.loginName+'&password='+md5($scope.account.password)+'&openId='+$rootScope.openId)).success(function (result) {
      if (result.successful) {
        // $localStorage.loginName = result.data.loginName;
        // $localStorage.nonce = result.data.nonce;
        // $localStorage.token = result.data.token;
        $scope.authError = false;
        $rootScope.logged = true;
        // $rootScope.userInfo = result.data.person;
        // $localStorage.userInfo=JSON.stringify($rootScope.userInfo);
        $state.go('admin.home');
      } else {
        $scope.authError = true;
      }
    });
  };
  $scope.forgetKey = function () {

    $state.go('tabs.findpassword', {}, {reload: false});
    $ionicHistory.clearHistory();
  }
})
  .controller('loadingCtrl', function ($rootScope, $state, $scope, $http, $localStorage, $location,$ionicLoading,$ionicPopup,$cordovaFileOpener2) {
    // $scope.getOpenInfo = function () {
    //   $http.get(API('huanbi/findUser?openId=') + $rootScope.openId).success(function (result) {
    //       if (result.successful) {
    //           if (result.data.cardId != null) {
    //               $rootScope.userMessage = true;
    //               $rootScope.userdata = result.data;
    //               $state.go($scope.route);
    //           }
    //       } else {
    //           $rootScope.userMessage = false;
    //       }
    //   })
    // };
    //   $scope.getOpenInfo();
    // $rootScope.ifUser =function () {
    //     if(!$rootScope.userMessage){
    //         var alertPopup = $ionicPopup.alert({
    //             title: '温馨提示!',
    //             template: '您的信息不全，无法预约,请绑定个人信息'
    //         });
    //         alertPopup.then(function(res) {
    //             $state.go('tabs.getUser');
    //         });
    //     }
    // };
    $scope.checkUpdate=function () {
      $http.get(API("app_version.json")).success(function (result) {
        console.info(JSON.stringify(result));
        if(result.version!=$rootScope.version){
          $ionicLoading.hide();
          var alertPopup = $ionicPopup.confirm({
            title: '<h3>版本更新</h3>',
            template: "检测到有新版本，是否更新到最新版本？" || ''
          });
          alertPopup.then(function (res) {
            if(res) {
              cordova.InAppBrowser.open(result.download,"_system")
              // UpdateForAndroid(result.downloadUrl);
            }
          });
        }
      })
    };
    //$scope.checkUpdate();


    //这个方法就是核心方法了    让你能实现版本的更新
    function UpdateForAndroid(source) {
      var target = "file:///sdcard/Download/ionic.apk";
      var trustAllHosts = true;
      var options = {};
      //FileTransfer这个类是cordova插件的方法，要使用文件下载new一个FileTransfer对象调用他的方法就好了
      var fileTransfer = new FileTransfer();

      /**这是官方给出的api 参数的解释  因为比较好懂这里需要注意下的是trustAllHosts参数
       *trustAllHosts这个参数决定了 你能否下载当trustAllHosts=false时你的下载的链接必须有安全凭证，
       * trustAllHosts=true的时候 你可以跳过安全凭证
       * Downloads a file form a given URL and saves it to the specified directory.
       * @param source {String}          URL of the server to receive the file
       * @param target {String}         Full path of the file on the device
       * @param successCallback (Function}  Callback to be invoked when upload has completed
       * @param errorCallback {Function}    Callback to be invoked upon error
       * @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
       * @param options {FileDownloadOptions} Optional parameters such as headers
       */
      function successCallback(entry) {
//   当下载成以后同过这个cordova方法你将打开你下载的最新app 固定格式 不做讲解 如果想知道cordova.plugins.fileOpener2插件的其他用法，可以看官方给的api
        console.info("准备安装...." + JSON.stringify(entry));
        $cordovaFileOpener2.open(target, 'application/vnd.android.package-archive').then(function () {
        }, function (err) {
          console.info(JSON.stringify(err));
        });
        console.info("安装完成....");
        $ionicLoading.hide();
      }

      function errorCallback(error) {
        //当apk下载失败做的操作
        $ionicLoading.show({
          template: "下载失败"
        });
        $timeout(function () {
          $ionicLoading.hide()
        }, 2000);
      }

      //这个方法就是执行下载apk的方法 参数一定要写对 上面有对应的参数 自行查看 就不做讲解了
      fileTransfer.download(source, target, successCallback, errorCallback, trustAllHosts, options);
      //onprogress 是fileTransfer的属性   他是通过回调函数来更新下载进度的
      fileTransfer.onprogress = function (progressEvent) {
        if (progressEvent.lengthComputable) {
          $ionicLoading.show({
            template: "已经下载：" + Math.floor((progressEvent.loaded / progressEvent.total) * 100) + "%"
          });
        }
      }
    }

  })



